#include <iostream>

using namespace std;

class TPoint {
	int X, Y;

public:
	TPoint(int x, int y) {
		X = x;
		Y = y; 
		cout << "Constructor called." << X << endl;
	}
	
	TPoint(const TPoint& p); //copy constructor
	
	~TPoint() { 
		cout << "Destructor called." << X << endl;
	}
	
	int Xcoord() { return X; }
	
	int Ycoord() { return Y; } 
};

TPoint::TPoint(const TPoint& p) {
	X = p.X; Y=p.Y;
	cout<< "Copy Constructor called." << X << endl; 
}

TPoint f(TPoint Q) // Pass by value -- Q调用拷贝构造
{ 
	cout << "OK! " << endl;
	int x, y;
	x=Q.Xcoord()+10;
	y=Q.Ycoord()+20;
	TPoint R(x, y); // 调用有参构造
	return R; // Return R’s data value -- 调用拷贝构造，利用R创建了temp
	
	// 函数f()结束后，调用析构函数：R、Q、temp -- 此编译器做了优化，结果不准确
}

int main() { 
	TPoint M(20,35), P(0,0);
	TPoint N=M; //M is a created object, N is a creating object
	P = f(N); // 赋值运算
	cout<<"P="<<P.Xcoord()<<", "<<P.Ycoord()<<endl; 
	return 0;
	
	/*
	正确结果：
		Constructor called.20
		Constructor called.0
		Copy Constructor called.20
		Copy Constructor called.20
		OK! 
		Constructor called.30
		Copy Constructor called.30
		Destructor called.30
		Destructor called.20
		Destructor called.30
		P=30, 55
		Destructor called.20
		Destructor called.30
		Destructor called.20
		
	*/
}
